<template>
  <div class="ellipsis-text">
    <div
      ref="textRef"
      class="ellipsis-text__value"
      :style="`-webkit-line-clamp: ${rows}`"
    >
      <span v-bind="textProps">{{ text || "-" }}</span>
      <CopyIcon
        v-if="!isEllipsis && copyable && text !== undefined"
        :text="text + ''"
        class="icon-copy"
      />
      <Tooltip
        v-if="tipType === 'tooltip' && isEllipsis"
        :text="text"
      ></Tooltip>
    </div>
    <CopyIcon
      v-if="isEllipsis && copyable && text !== undefined"
      class="icon-copy ellipsis-text__icon"
      :text="text + ''"
    />
  </div>
</template>
<script setup lang="ts">
import CopyIcon from "./CopyIcon.vue";
import { ref, computed } from "vue";
import Tooltip from "./Tooltip.vue";
const props = withDefaults(
  defineProps<{
    text?: string | number;
    copyable?: boolean;
    tipType?: "title" | "tooltip"; // title显示较慢，但是能自适应上下左右并且无视浏览器框；tooltip显示较快，但是会被浏览器视口所限制。
    rows?: number;
  }>(),
  { rows: 2, tipType: "tooltip" }
);
const textRef = ref();
const isEllipsis = computed(() => {
  return (
    textRef.value && textRef.value.scrollHeight > textRef.value.clientHeight
  );
});
const textProps = computed(() => {
  return isEllipsis.value && props.tipType === "title"
    ? { title: props.text === undefined ? props.text : props.text + "" } // 因为title只接受string和undefined
    : {};
});
</script>
<style scoped lang="css">
.ellipsis-text {
  position: relative;
}
.ellipsis-text__value {
  color: #040b29;
  min-height: 22px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}
.ellipsis-text__value:hover :deep(.tooltip) {
  opacity: 1;
  visibility: visible;
}
.icon-copy {
  margin-left: 4px;
}
.ellipsis-text__icon {
  display: inline-block;
  position: absolute;
  bottom: 0;
  right: -17px;
  z-index: 1;
}
</style>
